package com.basker.pisces.redis.counter;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.basker.pisces.concurrent.counter.AbstractCounterManager;
import com.basker.pisces.concurrent.counter.ICounter;

public class RedisCounterManager extends AbstractCounterManager implements InitializingBean {

    @Autowired
    private RedisConnectionFactory factory;

    private RedisTemplate<String, Integer> template;

    public RedisCounterManager(String name) {
        super(name);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        template = new RedisTemplate<>();

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericToStringSerializer<>(Integer.class));
        template.setConnectionFactory(factory);

        template.afterPropertiesSet();
    }

    @Override
    protected ICounter createCounter(String key) {
        return new RedisCounter(key, template);
    }

}
